// content.js

const list = new Set([]);

let titleElement = null; // 标题
let nextElement = null; // 下一曲
let playElement = null; // 播放
let pauseElement = null; // 暂停
let num = 0;
let maxNum = 50;
const isDownload = false;

let timeElement = null;

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (!isDownload) return;
  if (message.type === "audioUrl" && message.audioUrl) {
    // const id = getUrlParam("duration", message.audioUrl);
    if (list.has(titleElement.title)) {
      return;
    } else {
      list.add(titleElement.title);
      downloadFileFromBlob(titleElement.title, message.audioUrl);
      num++;
      if (num < maxNum) {
        setTimeout(() => {
          nextElement.click();
        }, 800);
      }
    }
  }
});

console.log("content.js");

const funNext = throttle(() => {
  nextElement.click();
}, 5000);

let interval = null; // 定时器
const timedTasks = () => {
  if (interval) {
    clearInterval(interval);
  }
  interval = setInterval(() => {
    const [time1, time2] = timeElement.textContent.split("/");
    const difference = Math.abs(timeToSeconds(time2) - timeToSeconds(time1));
    if (difference <= 15 && difference !== 0) {
      funNext();
    }
  }, 1000);
};

const observer = new MutationObserver((mutationsList, observer) => {
  nextElement = document.querySelector(".next");
  if (isDownload) {
    titleElement = document.querySelector(".fm-title");
    playElement = document.querySelector(".play");
    pauseElement = document.querySelector(".pause");
    if (titleElement && nextElement && (playElement || pauseElement)) {
      observer.disconnect(); // 找到目标元素后不再继续监控
    }
  } else {
    timeElement = document.querySelector(".xm-player-playtime");
    if (timeElement && nextElement) {
      observer.disconnect(); // 找到目标元素后不再继续监控
      timedTasks();
    }
  }
});
observer.observe(document, { childList: true, subtree: true });

// ----------------------------------------------------------------------

function getStorage(key = "list") {
  const str = localStorage.getItem(key);
  return str ? JSON.parse(str) : [];
}

function setStorage(key = "list", value = list) {
  localStorage.setItem(key, JSON.stringify(value));
}

// 获取url参数值
function getUrlParam(key, url = window.location.href) {
  try {
    // 创建一个新的URL对象
    const urlObject = new URL(url);
    // 使用URLSearchParams对象获取查询参数
    const params = new URLSearchParams(urlObject.search);
    // 返回查询参数的值
    return params.get(key);
  } catch (error) {
    console.error("Invalid URL:", error);
    return null;
  }
}

// 下载文件
function downloadFile(fileName, fileUrl) {
  // 创建一个隐藏的<a>元素用于触发下载
  const anchor = document.createElement("a");
  anchor.href = fileUrl;
  anchor.download = fileName;

  // 将元素添加到DOM中
  document.body.appendChild(anchor);

  // 触发下载
  anchor.click();

  // 下载完成后移除该元素
  document.body.removeChild(anchor);
}

function downloadFileFromBlob(fileName, fileUrl) {
  fetch(fileUrl)
    .then((response) => response.blob())
    .then((blob) => {
      const url = window.URL.createObjectURL(blob);
      const anchor = document.createElement("a");
      anchor.href = url;
      anchor.download = fileName;

      document.body.appendChild(anchor);
      anchor.click();
      document.body.removeChild(anchor);

      // 释放内存中的URL对象
      window.URL.revokeObjectURL(url);
    })
    .catch((error) => console.error("File download error:", error));
}

// 将时间字符串转化为秒数
function timeToSeconds(time) {
  const [hours, minutes, seconds] = time.split(":").map(Number);
  return hours * 3600 + minutes * 60 + seconds;
}

// 节流函数
function throttle(func, delay) {
  let lastTime = 0;

  return function (...args) {
    const now = new Date().getTime();
    if (now - lastTime >= delay) {
      lastTime = now;
      func.apply(this, args);
    }
  };
}
